package frame.PayDetail;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.PayDetailMapper;
import org.example.pojo.PayDetail;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class PayDetailupdate extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession;
    private PayDetailMapper payDetailMapper;

    public PayDetailupdate() {
        sqlSession = MyBatislianjian.getSqlSession();
        payDetailMapper = sqlSession.getMapper(PayDetailMapper.class);

        setTitle("修改采购明细信息");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
        table = new JTable() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return true; // 设置单元格可编辑
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // 设置多选模式

        // 初始化表格数据
        initializeTableData();

        // 将表格及其滚动面板添加到中心区域
        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板并添加到 SOUTH 区域
        JPanel buttonPanel = new JPanel();
        JButton updateButton = new JButton("确定修改");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updatePayDetails(); // 点击确定修改按钮时执行更新操作
            }
        });
        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new PayDetailPanel());
            }
        });
        buttonPanel.add(updateButton);
        buttonPanel.add(returnButton);
        this.add(buttonPanel, BorderLayout.SOUTH);

        // 设置内部窗口的大小和可见性
        setSize(800, 600);
        setVisible(true);
    }

    // 初始化表格数据
    private void initializeTableData() {
        Object[] columnNames = {"采购明细ID", "采购清单ID", "商品编号", "采购数量", "商品单价", "商品总价", "备注"};
        List<PayDetail> payDetails = payDetailMapper.selectAll();

        // 动态生成数据数组
        Object[][] data = new Object[payDetails.size()][columnNames.length];
        for (int i = 0; i < payDetails.size(); i++) {
            PayDetail payDetail = payDetails.get(i);
            data[i][0] = payDetail.getPDid();
            data[i][1] = payDetail.getPid();
            data[i][2] = payDetail.getGid();
            data[i][3] = payDetail.getPcount();
            data[i][4] = payDetail.getGpay();
            data[i][5] = payDetail.getTotal();
            data[i][6] = payDetail.getOther();
        }

        tableModel = new DefaultTableModel(data, columnNames);
        table.setModel(tableModel);

        // 添加表格编辑完成事件监听器，实时更新商品总价
        // 添加表格编辑完成事件监听器，实时更新商品总价
        table.getModel().addTableModelListener(e -> {
            if (e.getType() == TableModelEvent.UPDATE) {
                int row = e.getFirstRow();
                int column = e.getColumn();
                if (column == 3 || column == 4) { // 如果编辑的是采购数量或商品单价列
                    updateTotalForRow(row);
                }
            }
        });

    }

    // 更新单行的总价
    private void updateTotalForRow(int row) {
        Object pcountObj = table.getValueAt(row, 3);
        Object gpayObj = table.getValueAt(row, 4);

        // 检查并转换为整数和浮点数
        Integer pcount = null;
        if (pcountObj instanceof Integer) {
            pcount = (Integer) pcountObj;
        } else if (pcountObj instanceof String) {
            try {
                pcount = Integer.parseInt((String) pcountObj);
            } catch (NumberFormatException e) {
                // 处理无法转换的情况，可以在这里给出错误提示或者恢复原值
                JOptionPane.showMessageDialog(this, "采购数量必须是整数！", "错误", JOptionPane.ERROR_MESSAGE);
                // 如果需要恢复原值，可以重新设置表格的值
                table.setValueAt(null, row, 3); // 或者恢复原值
                return;
            }
        }

        Float gpay = null;
        if (gpayObj instanceof Float) {
            gpay = (Float) gpayObj;
        } else if (gpayObj instanceof String) {
            try {
                gpay = Float.parseFloat((String) gpayObj);
            } catch (NumberFormatException e) {
                // 处理无法转换的情况，可以在这里给出错误提示或者恢复原值
                JOptionPane.showMessageDialog(this, "商品单价必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
                // 如果需要恢复原值，可以重新设置表格的值
                table.setValueAt(null, row, 4); // 或者恢复原值
                return;
            }
        }

        if (pcount != null && gpay != null) {
            Float total = pcount * gpay;
            table.setValueAt(total, row, 5); // 更新表格中的总价列
        }
    }


    // 更新采购明细信息到数据库
    private void updatePayDetails() {
        int rowCount = table.getRowCount();
        boolean hasChanges = false; // 检查是否有任何数据变化

        for (int row = 0; row < rowCount; row++) {
            Integer pdid = null;
            Object value = table.getValueAt(row, 0);
            if (value instanceof Integer) {
                pdid = (Integer) value;
            } else if (value instanceof String) {
                pdid = Integer.parseInt((String) value);
            }

            Integer pid = null;
            value = table.getValueAt(row, 1);
            if (value instanceof Integer) {
                pid = (Integer) value;
            } else if (value instanceof String) {
                pid = Integer.parseInt((String) value);
            }

            String gid = (String) table.getValueAt(row, 2);

            Integer pcount = null;
            value = table.getValueAt(row, 3);
            if (value instanceof Integer) {
                pcount = (Integer) value;
            } else if (value instanceof String) {
                pcount = Integer.parseInt((String) value);
            }

            Float gpay = null;
            value = table.getValueAt(row, 4);
            if (value instanceof Float) {
                gpay = (Float) value;
            } else if (value instanceof String) {
                gpay = Float.parseFloat((String) value);
            }

            Float total = null;
            value = table.getValueAt(row, 5);
            if (value instanceof Float) {
                total = (Float) value;
            } else if (value instanceof String) {
                total = Float.parseFloat((String) value);
            }

            String other = (String) table.getValueAt(row, 6);

            // 检查关键字段不能为空字符
            if (gid.isEmpty() || pcount == null || gpay == null || total == null) {
                JOptionPane.showMessageDialog(this, "每一行的商品编号、采购数量、商品单价、商品总价都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 获取原始数据
            PayDetail originalPayDetail = payDetailMapper.queryPayDetailByPDid(pdid);
            if (originalPayDetail != null) {
                // 检查数据是否有变化
                if (!originalPayDetail.getPid().equals(pid)
                        || !originalPayDetail.getGid().equals(gid)
                        || !originalPayDetail.getPcount().equals(pcount)
                        || !originalPayDetail.getGpay().equals(gpay)
                        || !originalPayDetail.getTotal().equals(total)
                        || !originalPayDetail.getOther().equals(other)) {
                    // 更新数据库中的采购明细信息
                    PayDetail updatedPayDetail = new PayDetail(pid, gid, pcount, gpay, total, other);
                    updatedPayDetail.setPDid(pdid); // 更新时需要设置 PDid
                    payDetailMapper.updatePayDetail(updatedPayDetail);
                    hasChanges = true; // 标记有变化
                }
            }
        }

        if (hasChanges) {
            JOptionPane.showMessageDialog(this, "采购明细信息已更新！", "提示", JOptionPane.INFORMATION_MESSAGE);
            // 刷新表格数据
            refreshTableData();
        } else {
            JOptionPane.showMessageDialog(this, "没有检测到任何更改。", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // 刷新表格数据的方法
    private void refreshTableData() {
        List<PayDetail> payDetails = payDetailMapper.selectAll();

        // 清除现有数据
        tableModel.setRowCount(0);

        // 添加新的数据
        for (PayDetail payDetail : payDetails) {
            tableModel.addRow(new Object[]{
                    payDetail.getPDid(),
                    payDetail.getPid(),
                    payDetail.getGid(),
                    payDetail.getPcount(),
                    payDetail.getGpay(),
                    payDetail.getTotal(),
                    payDetail.getOther()
            });
        }
    }
}
